const express = require('express');
const router = express.Router();
const fs = require('fs');
const moment = require('moment');

router.get('/get', function(req, res, next) {
  // res.header('Access-Control-Allow-Headers', '*');
  const user = req.query.user;
  fs.readFile('./fs_data/healthy_info/' + user + '-2021-09-10.json', 'utf-8', function(error, data) {
    if (!error) {
      const value = JSON.parse(data);
      res.send(value);
    } else {
      res.send(false)
    }
  });
})

router.post('/login', function(req, res, next) {
  const user = req.body.user + '.txt';
  const password = req.body.password;
  fs.readFile('./fs_data/users/' + user, 'utf-8', function(error, data) {
    if (!error) {
      const value = data.replace(/\n/g, '');
      res.send(value === password);
    } else {
      res.send(false)
    }
  });
})

router.post('/add', function(req, res, next) {
  const data = req.body.form;
  const user = req.body.user;
  const fileName = moment().format('yyyy-MM-DD') + '.json'
  fs.appendFile('./fs_data/healthy_info/' + user + '-' + fileName, JSON.stringify(data), function(error) {
    if (error) {
      res.send(false)
    } else {
      res.send(true)
    }
  })
})


module.exports = router;
